#include "catalog/catalog.h"
int serializeTableMetadata(std::ofstream &os, TableMetadata *data) {
    os.open(data->name_ + ".meta", std::ios_base::out | std::ios_base::binary);
    if (!os.is_open()) {
        LOG_ERROR("Failed to open file for write. table name=%s, errmsg=%s", data->name_.c_str(), strerror(errno));
        return -1;
    }
    Json::Value table_meta_value;
    Json::Value schema_value;
    data->schema_.to_json(schema_value);
    table_meta_value[META_TABLE_SCHEMA] = schema_value;
    table_meta_value[META_NAME] = data->name_;
    table_meta_value[META_TABLE_FIRST_PAGE_ID] = data->table_->GetFirstPageId();
    table_meta_value[META_TABLE_ID] = data->oid_;
    Json::StreamWriterBuilder builder;
    Json::StreamWriter *writer = builder.newStreamWriter();
    std::streampos old_pos = os.tellp();
    writer->write(table_meta_value, &os);
    int ret = (int)(os.tellp() - old_pos);

    delete writer;
    return ret;
}

// 已经打开文件流
int deserializeMetadata(std::ifstream &is, TableMetadata &data) {
    Json::Value table_meta_value;
    Json::CharReaderBuilder builder;
    std::string errors;
    std::streampos old_pos = is.tellg();
    if (!Json::parseFromStream(builder, is, &table_meta_value, &errors)) {
        LOG_ERROR("Failed to deserialize table meta. error=%s", errors.c_str());
        return -1;
    }
    const Json::Value &schema_json = table_meta_value[META_TABLE_SCHEMA];
    Schema schema;
    Schema::from_json(schema_json, data.schema_);
    //  std::cout << "try desc:" << schema.ToString() << std::endl;
    const Json::Value &name_json = table_meta_value[META_NAME];
    // Schema::from_json(schema_json, data.schema_);

    data.name_ = name_json.asString();
    const Json::Value &page_id_json = table_meta_value[META_TABLE_FIRST_PAGE_ID];
    data.table_ = std::make_unique<TableHeap>(nullptr, nullptr, nullptr, page_id_json.asInt());
    data.oid_ = table_meta_value[META_TABLE_ID].asUInt();
}